package com.bussiness.system.controller;

import com.bussiness.system.service.SourceService;
import com.common.exception.ImageCodeIllegalException;
import com.common.exception.ImageTimeOutException;
import com.common.response.ResponseBean;
import com.common.response.ResponseCode;
import com.common.response.impl.BaseResponseImpl;
import com.common.util.VerifyUtil;
import com.common.vo.MenuVo;
import com.security.auth.ResponseUserToken;
import com.security.auth.UserDetail;
import com.security.service.AuthService;
import com.security.util.SecurityCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.List;


/**
 * @description:
 * @author: zyj
 * @create: 2020-01-03 17:06
 **/
@RestController
@Api(tags={"登陆相关"})
@RequestMapping("/auth")
public class AuthController extends BaseResponseImpl {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AuthService authService;
    @Autowired
    private SourceService sourceService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ApiOperation(value = "登陆", notes = "登陆成功返回token,登陆之前请先注册账号")
    public ResponseBean login(HttpServletRequest request,@RequestParam String userName, @RequestParam String passWord, @RequestParam(required = false) String imageCode){
        try {
            ResponseUserToken response = authService.login(userName, passWord, request);
            return successData(response);
        } catch (UsernameNotFoundException e) {
            e.printStackTrace();
            //用户名密码错误
            return errorCode(ResponseCode.LOGIN_ERROR.getValue());
        } catch (ImageTimeOutException e) {
            e.printStackTrace();
            //验证码超时
            return errorCode(ResponseCode.IMAGE_CODE_TIMEOUT.getValue());
        }catch (ImageCodeIllegalException e) {
            e.printStackTrace();
            //验证码错误
            return errorCode(ResponseCode.IMAGE_CODE_ERROR.getValue());
        } catch (Exception e) {
            e.printStackTrace();
            return error();
        }
    }

    @RequestMapping(value = "/testToken", method = RequestMethod.GET)
    @ApiOperation(value = "测试token")
    public ResponseBean testToken(){
        return success();
    }

    /**
     * 图片验证码
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/valicode", method = RequestMethod.GET)
    @ApiOperation(value = "获取验证码")
    public void valicode(HttpServletRequest request,HttpServletResponse response) throws Exception{
        HttpSession session = request.getSession();
        //利用图片工具生成图片
        //第一个参数是生成的验证码，第二个参数是生成的图片
        Object[] objs = VerifyUtil.createImage();
        //将验证码存入Session
        session.setAttribute(SecurityCode.IMG_CODE_SESSION.getCode(), objs[0]);
        session.setAttribute(SecurityCode.IMG_CODE_SESSION_TIME.getCode(), System.currentTimeMillis());

        //将图片输出给浏览器
        BufferedImage image = (BufferedImage) objs[1];
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
    }

    @RequestMapping(value = "/getUserUrl", method = RequestMethod.GET)
    @ApiOperation(value = "获取菜单信息")
    public ResponseBean getUserUrl(Authentication authentication){
        UserDetail userDetails = (UserDetail) authentication.getPrincipal();
        System.out.println(userDetails.getUsername()+"===User has authorities: " + userDetails.getAuthorities());
        Long userId = userDetails.getId();
        List<MenuVo> listMenu = null;
        try {
            listMenu = sourceService.getMenuVo(userId);
        } catch (Exception e) {
            logger.error("获取菜单信息失败！", e);
        }
        return successData(listMenu);
    }

    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户信息")
    public ResponseBean getUserInfo(){
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            UserDetail userDetails = (UserDetail) authentication.getPrincipal();
            return successData(userDetails);
        } catch (Exception e) {
            logger.error("获取用户失败！", e);
            return error();
        }
    }
}
